<?php
namespace app\admin\controller;

use app\common\model\Integral as IntegralModel;
use app\common\controller\AdminBase;
use think\Config;
use think\Db;

/**
 * 管理
 * Class Adminintegral
 * @package app\admin\controller
 */
class Integral extends AdminBase
{
    protected $integral_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->integral_model = new IntegralModel();
    }

    public function index($userName = '',$userPhone = '', $page = 1)
    {
        $map = [];
        $select = [];
        if($userName){
        	$map['name'] = ['like',"{$userName}"];
        }
        if($userPhone){
        	$map['phone'] = ['like',"{$userPhone}"];
        }
       
        if(!empty($map)){
        	$user_id = Db('user')->where($map)->where('status',1)->find();
        	$user_select_id = $user_id['id'];
        	if($user_select_id){
        		$select['userID'] = ['like',"{$user_select_id}"];
        	}else{
        		$select['userID'] = ['like',"0"];
        	}
        }
        
        $user_list = Db('user')->where('status',1)->select();
        $integral_list = $this->integral_model->where($select)->order('id DESC')->paginate(15, false, ['page' => $page]);

        return $this->fetch('index', ['integral_list' => $integral_list, 'userName' => $userName,'userPhone' => $userPhone,'user_list' => $user_list]);
    }

    public function edit($id)
    {
        $integral = $this->integral_model->find($id);
        $user_name = Db('user')->where('id',$integral['userID'])->where('status',1)->find();

        return $this->fetch('edit', ['integral' => $integral,'user_name' => $user_name['name']]);
    }

    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Integral');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->integral_model->allowField(true)->save($data,$id) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

}